#coding:utf-8
from PIL.ImageOps import expand
from _mysql import NULL
from win32security import SID
from PIL.FontFile import WIDTH
click_site=[]
defaultSiteList=[]
daterange=0
strarttime=""
endtime=""
import os
from Tkinter import *
import signal
from multiprocessing import Pool
import button.GetChinaNews
import button.cal
import calendar

def run_proc():
    print 'Run child process %s ' % (os.getpid())

def print_item(event):
    global defaultSiteList
    global click_site
    t.delete(0.0,END)
    a=(lb.get(lb.curselection()))
    click_site.append(a)
    defaultSiteList.append(a)
    #替换名称
    name=[]
    for i in defaultSiteList:
        if i=="SINA":
               name.append("新浪新闻")
        elif i=="163":
               name.append("网易新闻")
        elif i=="ZXW":
               name.append("中国新闻网")
        elif i=="HUAN":
               name.append("环球网")
    namelist=','.join(name)
    string="即将爬取的新闻网站为："
    t.insert("1.0",string+namelist)

def Button1(list):
    endtime=list.pop()
    starttime=list.pop()
    print list,starttime,endtime
    for i in list:
        button.GetChinaNews.defaultSiteList.append(i)
    print  button.GetChinaNews.defaultSiteList
    button.GetChinaNews.defaultStartTime=starttime
    button.GetChinaNews.defaultEndTime=endtime
    print button.GetChinaNews.defaultEndTime
    t=button.GetChinaNews.GetChinaNews(str_start_time=starttime,str_end_time=endtime)
    pid=button.GetChinaNews.get_pid()
    f = open("button/PID.txt",'wb')
    f.write(str(pid))
    f.close()
    t.getChinaNews()
    update_t('爬取完毕')

def Button2():
    f = open("button/PID.txt",'r')
    pid=f.readline()
    print "Stopping by user"
    update_t('已停止爬虫')
    os.popen("taskkill.exe /pid:"+str(pid)+" /F")

def clear():
    global defaultSiteList,click_site
    defaultSiteList=[]
    #button.GetChinaNews.defaultSiteList=[]
    click_site=[]
    t.delete(0.0,END)
    date1.delete(0.0,END)
    date2.delete(0.0,END)
def process():
    update_t('正在为你爬取对应网站........')
    global click_site,endtime,strarttime
    click_site.append(strarttime)
    click_site.append(endtime)
    pool.apply_async(Button1,[click_site],)
    

def update_t(mytext=""):
    t.delete(0.0, END)
    t.insert("1.0",mytext)

def getstart_date(evt):
    global daterange,strarttime,endtime
    x, y, widget = evt.x, evt.y, evt.widget
    item = widget.identify_row(y)
    column = widget.identify_column(x)

    if not column or not item in ttkcal._items:
        # clicked in the weekdays row or just outside the columns
        return

    item_values = widget.item(item)['values']
    if not len(item_values): # row is empty for this month
        return

    text = item_values[int(column[1]) - 1]
    if not text: # date is empty
        return

    bbox = widget.bbox(item, column)
    if not bbox: # calendar not visible yet
        return

    # update and then show selection
    text = '%02d' % text
    ttkcal._selection = (text, item, column)
    ttkcal._show_selection(text, bbox)
    if ttkcal._date.month<10:
        month="0"+str(ttkcal._date.month)
    datastring=str(ttkcal._date.year)+"-"+month+"-"+str(text)

    if daterange==0:
        date1.delete(0.0,END)
        date1.insert("1.0",datastring)
        strarttime=datastring
        daterange+=1
    else:
        date2.delete(0.0,END)
        date2.insert("1.0",datastring)
        endtime=datastring
        daterange-=1
if __name__=='__main__':
    root=Tk()
    root.geometry("400x320")
    root.resizable(width=False, height=True)
    frm=Frame(root)
    #创建进程池
    pool = Pool(processes=1)
    #This is for top frame
    '''
    frmtop=Frame(frm)
    Title_text= Label(frmtop, text="新闻信息网络爬虫系统", bg="#CCFFCC", font=("Arial", 12), width=200, height=2)
    Title_text.pack(side=TOP)
    frmtop.pack(side=TOP)'''
    root.title("新闻信息网络爬虫系统")
    

    #This is for right frame
    frmmin=Frame(frm)
    Button(frmmin,text='开始爬虫',command=process).pack()
    Button(frmmin,text='  清 空   ',command=clear).pack()
    Button(frmmin,text='  停 止   ',command=Button2).pack()
    frmmin.pack(side=RIGHT,expand=YES,padx=1,anchor=NE)


    #frmleft=Frame(frm,width=20,height=20)

    
    #ttkcal.pack_forget()

    ttkcal = button.cal.Calendar(firstweekday=calendar.SUNDAY)
    #ttkcal.pack(side=TOP,expand=YES,anchor=NE)
    #ttkcal.pack_forget()
    ttkcal.WIDTH=100
    ttkcal.pack(side=TOP)
    ttkcal._calendar.bind('<ButtonPress-1>',getstart_date)
    
    frm_1=Frame(root)
    begin_text=Label(frm_1, text="开始时间:")
    begin_text.pack(side=LEFT,expand=YES,padx=1,anchor=NW)
    date1=Text(frm_1,width=10,height=1)
    
    date1.pack(side=RIGHT,expand=YES,anchor=NW)
    frm_1.pack(side=TOP)
    
    frm_2=Frame(root)
    end_text=Label(frm_2, text="截至时间:")
    end_text.pack(side=LEFT)
    date2=Text(frm_2,width=10,height=1)
    date2.pack(side=RIGHT)
    frm_2.pack(side=TOP)
    #frmleft.pack(side=LEFT,pady=1,expand=YES,anchor=NW)
    
    
    
    #参考 http://www.cnblogs.com/zhangpengshou/p/3626137.html
    
    #This is for  bottom
    '''
    frmdown=Frame(frm)
    Button(frmdown,text='停止',command=Button2).pack()
    frmdown.pack(side=BOTTOM)
    '''
    #选择
    var = StringVar()
    lb = Listbox(frm,  listvariable = var,width=10,height=4)
    list_item = [1, 2, 3, 4]         #控件的内容为1 2 3 4
    var.set(('163', 'SINA', 'ZXW', 'HUAN'))   #重新设置了，这时控件的内容就编程var的内容了
    print var.get()
    lb.bind('<ButtonRelease-1>',print_item)
    lb.pack()

    frm.pack()
    
    frmdown_1=Frame(root)
    end_text=Label(frmdown_1, text="当前操作:")
    end_text.pack(side=LEFT)
    t=Text(frmdown_1,width=150,height=1)
    t.pack(side=RIGHT)
    frmdown_1.pack(side=TOP,expand=YES,anchor=NW)
    
    root.mainloop()
